package com.zhuangxiaoyan.spring.srcode.servlet;

import com.zhuangxiaoyan.spring.srcode.adapter.HandlerAdapter;
import com.zhuangxiaoyan.spring.srcode.adapter.impl.AnnotationtHandlerAdapter;
import com.zhuangxiaoyan.spring.srcode.adapter.impl.HttpRequestHandlerAdapter;
import com.zhuangxiaoyan.spring.srcode.controller.Controller;
import com.zhuangxiaoyan.spring.srcode.controller.impl.HttpController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Classname Dispathservlet
 * @Description TODO
 * @Date 2022/5/8 14:37
 * @Created by xjl
 */
public class DispathcherServlet {

    // 定义初始化Adaper集合
    private List<HandlerAdapter> handlerAdapters;

    public DispathcherServlet(){
        //初始化Adaper集合
        handlerAdapters=new ArrayList<HandlerAdapter>();
        handlerAdapters.add(new HttpRequestHandlerAdapter());
        handlerAdapters.add(new AnnotationtHandlerAdapter());
    }

    public HandlerAdapter getHandlerAdapter(Controller controller){
        if (this.handlerAdapters!=null){
            for (HandlerAdapter ha:this.handlerAdapters){
                if (ha.supports(controller)){
                    return ha;
                }
            }
        }
        return null;
    }


    public void dispathcher(){
        // 获取的handler
        HttpController httpController = new HttpController();
        // 获取具体的是适配器
        HandlerAdapter handlerAdapter = getHandlerAdapter(httpController);
        // 执行请求的方法
        handlerAdapter.handler(httpController);
    }

    public static void main(String[] args) {
        DispathcherServlet dispathcherServlet = new DispathcherServlet();
        dispathcherServlet.dispathcher();
    }
}
